<template>
  <div class="home-add">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="新闻标题" prop="newsTitle">
        <el-input v-model="ruleForm.newsTitle"></el-input>
      </el-form-item>
      <el-form-item label="阅读积分">
        <el-input
          size="small"
          v-model="ruleForm.newsIntegral"
          auto-complete="off"
          placeholder="请输入阅读积分"
        ></el-input>
      </el-form-item>
      <el-form-item label="新闻类型" prop="newsType">
        <el-select v-model="ruleForm.newsType" placeholder="请选择新闻类型" style="width:100%;">
          <el-option
            v-for="type in typeList"
            :label="type.key"
            :value="type.typeName"
            :key="type.typeName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="新闻时间" required>
        <el-col :span="11">
          <el-form-item prop="newsTime">
            <el-date-picker
              type="datetime"
              placeholder="选择日期"
              v-model="ruleForm.newsTime"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="新闻图片">
        <el-upload
          action="/apis/user/uploadImg"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <el-form-item label="新闻内容" prop="newContent">
        <Editor v-model="ruleForm.newContent" />
      </el-form-item>
      <el-form-item style="  margin-top: 80px;text-align: center;">
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Editor from "../Comm/editor";
import { userNewsSave_user, typeListAll_user } from "../../ajax/index";
export default {
  data() {
    return {
      typeList: [],
      ruleForm: {
        newsTitle: "",
        newsType: "",
        newsTime: "",
        newContent: "",
        newsIntegral: "",
        newsImg: []
      },
      rules: {
        newsTitle: [
          { required: true, message: "请输入新闻标题", trigger: "blur" },
          { min: 3, message: "不少于3个字符", trigger: "blur" }
        ],
        newsType: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ],
        newsTime: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        newContent: [
          { required: true, message: "请填写活动形式", trigger: "blur" }
        ]
      },
      dialogVisible: false,
      dialogImageUrl: ""
    };
  },
  created() {
    this.getTypeAll();
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        this.ruleForm.newsImg = this.ruleForm.newsImg.map(item => item.url);
        if (valid) {
          userNewsSave_user(this.ruleForm)
            .then(res => {
              if (res.code) {
                this.$message({
                  type: "success",
                  message: "新闻提交成功！"
                });
                this.$router.push({ path: "/home" });
              } else {
                this.$message({
                  type: "info",
                  message: res.msg
                });
              }
            })
            .catch(err => {
              this.$message.error("新闻保存失败，请稍后再试！");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleRemove(file, fileList) {
      for (const i in this.ruleForm.newsImg) {
        if (this.ruleForm.newsImg[i].key === file.uid) {
          this.ruleForm.newsImg.splice(i, 1);
        }
      }
    },
    handlePictureCardPreview(file, fileList) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      if (file.response.code) {
        this.ruleForm.newsImg.push({
          url: file.response.url,
          uid: file.uid
        });
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPng = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error("上传图片只能是 JPG或png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return (isJPG || isPng) && isLt2M;
    },
    getTypeAll() {
      typeListAll_user().then(res => {
        if (res.code) {
          this.typeList = res.data.data;
        }
      });
    }
  },
  components: {
    Editor
  }
};
</script>

<style lang="scss" scoped>
.demo-ruleForm {
  margin-top: 40px;
}
</style>